﻿package framework.core;

import java.sql.ResultSet;
import java.util.ArrayList;

public class SelectBase 
{
	private static boolean compareStr(String str1, String str2) 
	{
		if (str1 == null) str1 = "";
		if (str2 == null) str2 = "";
		return str1.equals(str2);
	}

	private static String printOption(String currVal,String value,String display,String custom) 
	{
			String ret = "";
			ret += "  <option value='" + value + "'";
			if(custom==null) custom="";
			ret += " " + custom + " " ;
			if (compareStr(currVal, value)) {
				ret += " selected";
			}
			ret += ">" + display + "</option>\n";
			return ret;
	}
	private static String printOption(String currVal,SelectOption option) 
	{
		if(null==option) return "";
		return printOption(currVal,option.getValue(),option.getDisplay(),option.getCustom());
	}
	protected static String viewSelect(ArrayList options,String selectName,String currVal,
										SelectOption allOption,String custom) 	throws Exception
	{
			//String s = "<select name='" + selectName + "' " + custom + ">";
			String s = "<select name='" + selectName + "' " + custom + " style='width:130px'>";
			s += printOption(currVal,allOption);
			if(options!=null)
			{
				for (int i = 0; i < options.size(); i++) 
				{
					SelectOption option = (SelectOption)options.get(i);
					s += printOption(currVal,option);
				}
			}
			s += "</select>";
			return s;
	}
	
	protected static String viewSelect(ArrayList options,String selectName,String currVal,
											boolean needAll,String allValue,String allDisplay,String allCustom,
											String custom) 	throws Exception
	{
			SelectOption allOption = null;
			if(needAll) allOption = new SelectOption(allValue,allDisplay,allCustom);
			return viewSelect(options,selectName,currVal,allOption,custom);
	}
	
	//根据sql生成下拉框,sql中 字段1 为value,字段2 为display
	protected static String viewSelect(DBConnection con,String sql,String selectName,String currVal,
												boolean needAll,String allValue,String allDisplay,String allCustom,
												String custom) 	throws Exception
	{
		DBResult result = DBEngine.doSelect(con,sql);
		ResultSet rs = result.getRs();
		ArrayList options = new ArrayList();
		while(rs.next())
		{
			SelectOption option = new SelectOption();
			option.setValue(rs.getString(1));
			option.setDisplay(rs.getString(2));
			options.add(option);
		}
		result.clear();
		return viewSelect(options,selectName,currVal,needAll,allValue,allDisplay,allCustom,custom);
	}
	
	

	
	//view page size selecter
	public static String viewPageSizeSelect(DBConnection con,String selectName,String currVal) throws Exception 
	{
		ArrayList options = new ArrayList();
		options.add(new SelectOption("10","每页显示10条"));
		options.add(new SelectOption("20","每页显示20条"));
		options.add(new SelectOption("50","每页显示50条"));
		options.add(new SelectOption("100","每页显示100条"));
		return viewSelect(options,selectName,currVal,null,"");
	}
	
	
}